package com.chen.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.BaseContext;
import com.chen.common.R;
import com.chen.dto.OrdersDto;
import com.chen.entity.Dish;
import com.chen.entity.OrderDetail;
import com.chen.entity.Orders;
import com.chen.entity.ShoppingCart;
import com.chen.service.DishService;
import com.chen.service.OrderDetailService;
import com.chen.service.OrderService;
import com.chen.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private DishService dishService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 手机查询订单
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize) {

        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();

        Long userId = BaseContext.getCurrentId();

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId,userId);
        lqw.orderByDesc(Orders::getCheckoutTime);

        orderService.page(ordersPage,lqw);

        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");

        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> list = records.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);

            LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(OrderDetail::getOrderId, item.getNumber());
            List<OrderDetail> orderDetailList = orderDetailService.list(lqw2);

            if (orderDetailList != null && orderDetailList.size() != 0) {
                ordersDto.setOrderDetails(orderDetailList);
            }
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(list);
        return R.success(ordersDtoPage);

    }

    /**
     * 后台查询订单
     */
    @GetMapping("/page")
    public R<Page> backendPage(int page , int pageSize, Long number, String beginTime, String endTime){
        log.info("page:{},pageSize:{},number{},beginTime:{},endTime:{}",page,pageSize,number,beginTime,endTime);

        Page<Orders> pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        if (number !=null){
            lqw.eq(Orders::getNumber,number);
        }
        if (StringUtils.isNotEmpty(beginTime) &&StringUtils.isNotEmpty(endTime)){
            LocalDateTime begin = LocalDateTime.parse(beginTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime end = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            lqw.between(Orders::getOrderTime,begin,end);
        }
        orderService.page(pageInfo, lqw);
        return R.success(pageInfo);

    }

    /**
     * 派送
     */

    @PutMapping
    public R<String> delivery(@RequestBody Orders orders){
        log.info("orders:{}" ,orders);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getId,orders.getId());
        //查询此订单
        Orders order = orderService.getOne(lqw);
        //将状态设置进去
        order.setStatus(orders.getStatus());
        //修改状态
        orderService.updateById(order);
        return R.success("派送成功");
    }

    /**
     * 再来一单
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        log.info("id:{}",orders.getId());
        //判断当前用户的购物车有无菜品/套餐
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartService.list(lqw);
        if (list.size() > 0){
            //如果有先删除购物车所有东西
            shoppingCartService.remove(lqw);
        }
        //把当前订单的菜品添加到购物车里
        //先查询当前订单的所有菜品
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> list1 = orderDetailService.list(queryWrapper);
        for (OrderDetail orderDetail : list1) {
            //吧所有菜品添加到购物车里
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        }
        return R.success("再来一单");
    }
}